//
//  MIDIjoinController.m
//  迷笛
//
//  Created by . on 2018/9/13.
//  Copyright © 2018年 🍃🌺🌺🍃. All rights reserved.
//

#import "MIDIjoinController.h"
#import "MIDIJoinCell.h"
#import "MIDIjoinmodel.h"
@interface MIDIjoinController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView * jonintable;
@property (nonatomic,retain) NSArray *viewControllers;
@property(nonatomic,copy)NSString *Myjoinapi;
@property(nonatomic,copy)NSString * apptoken;

@property(nonatomic,strong)NSMutableArray * joinArr;
@property(nonatomic,copy)NSString * outapi;

@property(nonatomic,copy)NSString * praiseapi;
@end

@implementation MIDIjoinController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    self.apptoken = [user objectForKey:@"APPToken"];
//    [self MyjoinRequest];
//    self.joinArr = [NSMutableArray array];
    self.view.backgroundColor =[UIColor colorWithHexString:@"#171717"];
    [self HomeUI];
}
 - (void)viewDidAppear:(BOOL)animated
 {
    [super viewDidAppear:animated];
     [self MyjoinRequest];
     self.joinArr = [NSMutableArray array];
 }
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
    return self.joinArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString * cellID = @"cell";
    MIDIJoinCell * cell =[tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell)
    {
        cell =[[MIDIJoinCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
        cell.backgroundColor =[UIColor colorWithHexString:@"#1B212F"];
        [_jonintable setSeparatorColor : [UIColor blackColor]];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;

    }
    MIDIjoinmodel * mm1 = self.joinArr[indexPath.row];
    
    [cell.heardimgea sd_setImageWithURL:[NSURL URLWithString:mm1.cover] placeholderImage:nil];
    cell.name.text =mm1.name;
    cell.fous.text = [NSString stringWithFormat:@"关注%@",mm1.join];
    cell.post.text = [NSString stringWithFormat:@"帖子数%@",mm1.post];
    
    [cell.recommendFocusBtn setBackgroundColor:[UIColor colorWithHexString:@"#999999"]];
    [cell.recommendFocusBtn setTitle:@"已加入" forState:UIControlStateNormal];
    cell.recommendFocusBtn.selected = YES;
    cell.recommendFocusBtn.tag = indexPath.row;

    [cell.recommendFocusBtn addTarget:self action:@selector(fousbtn:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kDevice_Is_iPhoneX?HeighX(70):HeightScale(70);
}
- ( UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;
{
    return nil;
}
- ( UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;
{
    return nil;
}
-(void)fousbtn:(UIButton * )sender
{
    
    
    if (sender.selected == YES)
    {
        sender.selected=!sender.selected;//每次点击都改变按钮的状态

        
            UIAlertController *controller=[UIAlertController alertControllerWithTitle:@"确认不再加入此圈？" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
            UIAlertAction *act1=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
            }];
            [act1 setValue:[UIColor colorWithHexString:@"#171717"] forKey:@"titleTextColor"];
        
            UIAlertAction *act2=[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
                {
                    [self outcircle:sender.tag];
                    MIDIJoinCell *selCell = [self.jonintable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:sender.tag inSection:0]];
                    MIDIjoinmodel *selModel = self.joinArr[sender.tag];
                    NSString *origenAttentionNum = selModel.join;
                    selModel.join = [NSString stringWithFormat:@"%ld",[origenAttentionNum integerValue] - 1];
                    selCell.fous.text = [NSString stringWithFormat:@"%@%@",@"关注",selModel.join];
                    
                    [self outcircle:sender.tag];
                    [sender setBackgroundColor:[UIColor colorWithHexString:@"#FF005D"]];
                    
                    [sender setTitle:@"加入" forState:UIControlStateNormal];
                    
                    
                }];
        
            [act2 setValue:[UIColor colorWithHexString:@"#FF005D"] forKey:@"titleTextColor"];
            [controller addAction:act1];
            [controller addAction:act2];
            [self presentViewController:controller animated:YES completion:^{
            }];

    }
    
    else
    {
        NSNumber *typeNumber = [self.joinArr[sender.tag] modelId];
        //
        _praiseapi = [NSString stringWithFormat:@"%@circle/join/%@?token=%@",MIDIApiRoot,typeNumber,_apptoken];
        //
        NSLog(@"praiseRequest--%@",_praiseapi);
        //
        [EdHttp get:_praiseapi params:nil progress:^(id downloadProgress)
         {
             
         }
            success:^(id responseObject)
         {
             sender.selected=!sender.selected;//每次点击都改变按钮的状态
             NSLog(@"加入成功%@",responseObject);
             if ([[responseObject objectForKey:@"code"] isEqualToNumber:@200])
             {
                 
                 MIDIJoinCell *selCell = [self.jonintable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:sender.tag inSection:0]];
                 MIDIjoinmodel *selModel = self.joinArr[sender.tag];
                 NSString *origenAttentionNum = selModel.join;
                 selModel.join = [NSString stringWithFormat:@"%ld",[origenAttentionNum integerValue] + 1];
                 selCell.fous.text = [NSString stringWithFormat:@"%@%@",@"关注",selModel.join];
                 
                 //第一次点击为蓝色（关注）
                 MIDIjoinmodel *model = self.joinArr[sender.tag];
                 model.isjoin = @1;
                 [sender setBackgroundColor:[UIColor colorWithHexString:@"#999999"]];
                 [sender setTitle:@"已加入" forState:UIControlStateNormal];
                 [sender setAccessibilityFrame:CGRectMake(0, 0, WidthScale(100), HeightScale(40))];
                 
                 [SVProgressHUD showSuccessWithStatus:@"加入圈子成功"];
                 [SVProgressHUD dismissWithDelay:1.0];
                 NSLog(@"已关注");
             }
             else
             {
                 NSLog(@"加入失败");
             }
         }
            failure:^(NSError *error)
         {
             NSLog(@"失败");
         }];
        
    }
    
    
}

-(void)HomeUI
{
    [self.view addSubview:self.jonintable];
}
-(UITableView *)jonintable
{
    if (!_jonintable)
    {
        _jonintable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 70) style:UITableViewStyleGrouped];
        _jonintable.dataSource = self;
        _jonintable.delegate = self;
        _jonintable.backgroundColor = [UIColor colorWithHexString:@"#1B212F"];
        //        _Hottable.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _jonintable;
}
-(void)MyjoinRequest
{
    NSString * circle = @"users/circle";
    self.Myjoinapi = [NSString stringWithFormat:@"%@%@?token=%@",MIDIApiRoot,circle,self.apptoken];
    NSLog(@"地址%@",self.Myjoinapi);
    [EdHttp get:self.Myjoinapi params:nil progress:^(id downloadProgress)
     {
         
     }
        success:^(id responseObject)
     {
         NSLog(@"我加入的圈子%@",responseObject);
         NSArray *arr4 = responseObject[@"data"];
         for (NSDictionary *dic4 in arr4)
         {
             NSString * circlename;
             NSString * circleiamge;
             NSString * join_peopel;
             NSString * post_people;
             NSNumber * is_join;
             if (![dic4[@"name"] isKindOfClass:[NSNull class]]){
                 circlename = dic4[@"name"];
             }
             else{
                 circlename = @"";
             }
             if (![dic4[@"cover"] isKindOfClass:[NSNull class]]){
                 circleiamge = dic4[@"cover"];
             }
             else{
                 circleiamge = @"";
             }
             if (![dic4[@"join_peopel"] isKindOfClass:[NSNull class]]){
                 join_peopel = dic4[@"join_peopel"];
             }
             else{
                 join_peopel = @"";
             }
             if (![dic4[@"post_people"] isKindOfClass:[NSNull class]]){
                 post_people = dic4[@"post_people"];
             }
             else{
                 post_people = @"";
             }
             if (![dic4[@"is_join"] isKindOfClass:[NSNull class]]){
                 is_join = dic4[@"is_join"];
             }
             else{
                 //                 is_join = @"";
             }
             
             MIDIjoinmodel * mmact = [MIDIjoinmodel new];
             mmact.modelId = dic4[@"id"];
             mmact.name = circlename;
             mmact.cover =circleiamge;
             mmact.join = join_peopel;
             mmact.post = post_people;
             mmact.isjoin = is_join;
             
             [self.joinArr addObject:mmact];
//             [self.jonintable reloadData];

         }
         dispatch_async(dispatch_get_main_queue(), ^{
             [self.jonintable reloadData];
         
         });
     }
        failure:^(NSError *error)
     {
         NSLog(@"失败");
     }];
}
-(void)outcircle:(NSInteger)indexRow
{
    NSNumber * typeNumber = [self.joinArr[indexRow] modelId];
    
    self.outapi = [NSString stringWithFormat:@"%@circle/out/%@?token=%@",MIDIApiRoot,typeNumber,_apptoken];
    
    NSLog(@"praiseRequest--%@",self.outapi);
    
    [EdHttp get:_outapi params:nil progress:^(id downloadProgress)
     {
         
     }
        success:^(id responseObject)
     {
         NSLog(@"退出圈子%@",responseObject);
         if ([[responseObject objectForKey:@"code"] isEqualToNumber:@200])
         {
             MIDIjoinmodel *model = self.joinArr[indexRow];
             model.isjoin = @0;
           
             
             
            [SVProgressHUD showSuccessWithStatus:@"退出圈子成功"];
             [SVProgressHUD dismissWithDelay:1.0];

             NSLog(@"退出成功");
         }
         else
         {
             NSLog(@"失败");
         }
     }
        failure:^(NSError *error)
     {
         NSLog(@"失败");
     }];
}
@end
